<?php
if (!function_exists('get_addon_info'))
{
    function get_addon_info($name)
    {

    }
}
if (!function_exists('get_addon_class'))
{
    /**
     * 获取插件类的类名
     * @param string $name 插件名
     * @param null $class 当前类名
     * @return string
     */
    function get_addon_class(string $name, $class = null):string
    {
        return app()->parseClass($class,$name);
    }
}
if (!function_exists('get_addon_instance'))
{
    /**
     * 获取插件的单例
     * @param string $name 插件名
     * @return mixed|null
     */
    function get_addon_instance(string $name)
    {
        $range = config('addons.container_name')?:'addons';
        $container_name = app()->exists($range.'.'.$name);
        return app()->make($container_name,[],true);
    }
}
if (!function_exists('get_addon_config'))
{
    /**
     * 获取插件类的配置值值
     * @param string $name 插件名
     * @return array|string
     */
    function get_addon_config(string $name)
    {
        $addon = get_addon_instance($name);
        if (!$addon) {
            return [];
        }
        return $addon->getConfig($name);
    }
}
if (!function_exists('get_addon_info'))
{
    /**
     * 读取插件的基础信息
     * @param string $name 插件名
     * @return array|string
     */
    function get_addon_info(string $name)
    {
        $addon = get_addon_instance($name);
        if (!$addon) {
            return [];
        }
        return $addon->getInfo($name);
    }
}
if (!function_exists('addon_url'))
{
    /**
     * 插件显示内容里生成访问插件的url
     * @param string $url 地址 格式：插件名/控制器/方法
     * @param array $vars 变量参数
     * @param bool|string $suffix 生成的URL后缀
     * @param bool|string $domain 域名
     * @return bool|string
     */
    function addon_url(string $url, $vars = [], $suffix = true, $domain = false)
    {
        if (strstr($url,'.')!==false)
        {
            $build_vars = explode('.',$url);
            if (count($build_vars)>=3)
            {
                [$addon,$controller,$action] = $build_vars;
                $vars = array_merge(compact('addon','controller','action'),$vars);
            }
        }elseif (strstr($url,'/')!==false)
        {
            $build_vars = explode('/',$url);
            if (count($build_vars)>=3)
            {
                [$addon,$controller,$action] = $build_vars;
                $vars = array_merge(compact('addon','controller','action'),$vars);
            }
        }
        return url('addons',$vars,$suffix,$domain)->build();
    }
}
if (!function_exists('addon_path'))
{
    /**
     * 插件目录
     * @param $path
     * @return string
     */
    function addon_path($path): string
    {
    $addons_path = config('addons.addons_path')?:'addons';
    return root_path($addons_path.DIRECTORY_SEPARATOR.$path);
    }
}
if (!function_exists('set_addon_info'))
{
    /**
     * 设置基础配置信息
     * @param string $name 插件名
     * @param array $array 配置数据
     * @return boolean
     * @throws Exception
     */
    function set_addon_info(string $name, array $array): bool
    {
        $file =addon_path($name). 'info.ini';
        $addon = get_addon_instance($name);
        $array = $addon->setInfo($name, $array);
        if (!isset($array['name']) || !isset($array['title']) || !isset($array['version'])) {
            throw new Exception("插件配置写入失败");
        }
        $res = array();
        foreach ($array as $key => $val) {
            if (is_array($val)) {
                $res[] = "[$key]";
                foreach ($val as $skey => $sval) {
                    $res[] = "$skey = " . (is_numeric($sval) ? $sval : $sval);
                }
            } else {
                $res[] = "$key = " . (is_numeric($val) ? $val : $val);
            }
        }
        if ($handle = fopen($file, 'w')) {
            fwrite($handle, implode("\n", $res) . "\n");
            fclose($handle);
        } else {
            throw new Exception("文件没有写入权限");
        }
        return true;
    }
}

if (!function_exists('set_addon_config'))
{
    /**
     * 写入配置文件
     * @param string  $name      插件名
     * @param array   $config    配置数据
     * @param boolean $writefile 是否写入配置文件
     * @return bool
     * @throws Exception
     */
    function set_addon_config($name, $config, $writefile = true): bool
    {
        $addon = get_addon_instance($name);
        $addon->setConfig($name, $config);
        $fullconfig = set_addon_full_config($name);
        foreach ($fullconfig as $k => &$v) {
            if (isset($config[$v['name']])) {
                $value = $v['type'] !== 'array' && is_array($config[$v['name']]) ? implode(',', $config[$v['name']]) : $config[$v['name']];
                $v['value'] = $value;
            }
        }
        if ($writefile) {
            // 写入配置文件
            set_addon_full_config($name, $fullconfig);
        }
        return true;
    }
}
if (!function_exists('set_addon_full_config'))
{
    /**
     * 写入配置文件
     *
     * @param string $name 插件名
     * @param array $array 配置数据
     * @return boolean
     * @throws Exception
     */
    function set_addon_full_config(string $name, array $array): bool
    {
        $file = addon_path($name) . 'config.php';
        if (!is_really_writable($file)) {
            throw new Exception("文件没有写入权限");
        }
        if ($handle = fopen($file, 'w')) {
            fwrite($handle, "<?php\n\n" . "return " . \Symfony\Component\VarExporter\VarExporter::export($array) . ";\n");
            fclose($handle);
        } else {
            throw new Exception("文件没有写入权限");
        }
        return true;
    }
}
if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}
if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}